var addIndex_S = 1;// 医嘱内容id自增

/* 手术表格展示 */

function shoushuTable()
{
	var params = activeTabParam();
	var that = this;
	var dataStr = $("#dataStr").val();
	var dataObj = dataStr ? JSON.parse(dataStr) : '';
	/* js增加表头的checbox,为了不使用icheck */
	theadAddCheckox(params.tableId);
	shoushuAddTr(-1);
	ssChoseTr();
//	ssDeleteTr();
//	if (dataObj)
//	{
//		editShoushuAdvice(dataObj)// 手术编辑
//	}
	fujiaSsAdd();
}

// 附加手术添加

function fujiaSsAdd()
{
	$(".shoushu_fjss").on("click", function()
	{
		var data = {};
		var curTbody = $(this).parents("tbody");
		laytplUrl(myurl + "/module/shaoshu_add_table.html", data, function(data, html)
		{
			var index = layer.open(
			{
			type : 1,
			scrollbar : false,
			title : "附加手术",
			area : [
			"40%", "40%"
			],
			shade : 0.1,
			// maxmin : true,
			content : html,
			closeBtn : 1,
			success : function()
			{
				$(".fjssx_select").append(fujianshoushuListHtml);
				// $(".mz_select").append(mazuiHtml);
				addFjss_btn();
				fujiassListShow(curTbody);
				$("#remove_action_ss").on("click", function()
				{
					layer.close(index);
				})
				$(".fjssx_select").find("select").select2();
			}
			})

		});
	})

}

// 继续添加附加手术
function addFjss_btn()
{
	$("#add_fjss").on("click", function()
	{
		
		var html ='<div class="form-group inline">'
			+'<span class="col-sm-2 control-label" style="padding: 7px 0 0 15px; text-align: right;">附加手术项 </span>'
			+'<div class="col-sm-4  fjssx_select"></div>'
			+'<span class="col-sm-2 control-label " style="padding: 7px 0 0 15px; text-align: right;">手术类型 </span>'
			+'<div class="col-sm-4  sslx_select">'
				+'<select class="form-control">'
					+'<option>1</option>'
					+'<option>2</option>'
					+'<option>3</option>'
					+'<option>4</option>'
					+'<option>5</option></select></div></div>'
		$("#ssxm_add").append(html);
		$("#ssxm_add").find(".fjssx_select").last().append(fujianshoushuListHtml);
		$("#ssxm_add").find(".fjssx_select").last().find("select").select2();
	})
}
// 附加手术加载到手术页面
function fujiassListShow(curTbody)
{
	var fujiaArr = [];
	var i = 0;
	$("#add_fujiass").on("click", function()
	{
		$(".fjssx_select").each(function(index, ele)
		{
			if ($(ele).find("select").val().trim())
			{
				var id = $(ele).find("select option:selected").attr("id");
				var fjss_idArr = id.split('|');
				var fjss_id = fjss_idArr[1];
				var fjss_val = $(ele).find("select").val().trim();
				var obj = {};
				obj.fjss_id = fjss_id;
				obj.fjss_val = fjss_val;
				fujiaArr.push(obj);//

			}
		});
		$(".shoushu_fjss").each(function(index, ele)
		{// 有空的input，追加添加
			if ($(ele).val() == "")
			{

				/*获取最做能存放的附加手术*/
				var times = (8-index+1)<=fujiaArr.length ?(8-index+1):fujiaArr.length;
				if ( i < times)
				{
					$(ele).val(fujiaArr[i]["fjss_val"]);
					$(ele).next().val(fujiaArr[i].fjss_id);
					i++;
				}
			}
		});
		
		setSsAdviceboxEvent(curTbody);
		layer.closeAll();// 关闭弹出层
	})
}

// 手术新增一行
function ssAdTr()
{
	var params = activeTabParam();
	var sstdList = $("#"+params.tableId).find(".shoushu_yznr").last();
	$(sstdList).focus();
	$(sstdList).keydown(function(e)
	{
		if (e.which === 40)
		{
			if($(".select2-container--open").length<1 &&($(".smart_search").length<1))
	   		  {
					var that = this;
					var next = $(this).parents("tr").next().find(".shoushu_yznr");
					var last = $(this).parents("tbody").find(".shoushu_yznr").last();
					if(((next.val()||next.length<1)&&$(this).val())&&(last.val()&&$(this).val())){
						
						shoushuAddTr(that);
					}else {
						next.focus();
					}
	   		  }
		}
	})
}

/* 按钮增加行 */
function ss_addTrBtnEvent()
{
	var params = activeTabParam();
	var sstdList = $("#"+params.tableId).find(".shoushu_yznr").last();
	var id = $(sstdList).parents("tr").find(".shoushu_yznr").attr("id");
	inputId = $("#" + id)
	shoushuAddTr(inputId);
}
// 手术新增一行TR
function shoushuAddTr(inputId)
{
	var params = activeTabParam();
	laytplUrl_T(myurl + "/module/xk_shaoshu_table.html", {}, function(data, html)
	{
		if (inputId != -1)
		{
			$(inputId).parents("tbody").after(html);
		}
		else
		// 第一行
		{
			$("#"+params.tableId).append(html);
		}
		var yizhuId = $(".shoushu_yznr").last().attr("id");
		inputEvent(yizhuId);
		var lastTimeInput = $("#"+params.tableId).find(".shoushu_kssj").last();
		var shoushushijian = $("#"+params.tableId).find(".shoushu_sssj").last();
		setTime(lastTimeInput);// 设置开始时间
		setTime(shoushushijian);// 设置手术时间
		ssAdTr();// 医嘱内容增加回车事件
		$(".shoushu_zxks").children().find("option:contains('手术')").attr("selected","selected").trigger("change");//设置手术默认执行科室为手术室
		$(".shoushu_mzzx").children().find("option:contains('麻醉')").attr("selected","selected").trigger("change");//设置麻醉默认执行科室为麻醉室
		$(".shoushu_zu").last().text(addIndex_S);
		addIndex_S++;// 医嘱内容id自增
		// select2 美化
		$("#"+yizhuId).parents("tbody").find("select").select2();
		//icheck初始化
		iChenckInit($("#"+yizhuId).parents("tr").find('input:eq(0)'));
		isChoseAll(params.tableId);
		
		$("#"+yizhuId).parents("tbody").find(".shoushu_mzfs").find("select").on('change', function(event){
			var curTbody = $(this).parents("tbody");
			setSsAdviceboxEvent(curTbody);
		});
		$("#"+yizhuId).parents("tbody").find(".shoushu_sssj").on('change', function(event){
			var curTbody = $(this).parents("tbody");
			setSsAdviceboxEvent(curTbody);
		});
	});
}

/* 麻醉方式和附加手术拼接手术医嘱内容 */
function setSsAdviceboxEvent($thistbody)
{
	debugger;
	var yizhu_text = $($thistbody).find(".shoushu_yznr").attr("data-name").trim();  //医嘱内容
	var mazui_text =   $($thistbody).find(".shoushu_mzfs").find("option:selected").text();//麻醉
	if(mazui_text==""){
		mazui_text = "无麻醉";
	}
	//附加手术
	var fuss_text = '';
	$($thistbody).find(".shoushu_fjss").each(function(i,ele){
		if($(ele).val()){
			fuss_text +=$(ele).val()+'，';
		}
	});
	if(fuss_text.charAt(fuss_text.length-1)=="，")
	{
		fuss_text = fuss_text.substring(0, fuss_text.length-1);
	}
	if(fuss_text){
		fuss_text = '及 ' +fuss_text;
	}
	//日期
	var ss_data =  $($thistbody).find(".shoushu_sssj").val();
	var shoushu_buwei = $thistbody.find(".shoushu_buwei").val();
	var buwei = (!!shoushu_buwei)?"("+$thistbody.find(".shoushu_buwei").val()+")":"";
	var html="";
	//“2018-03-15 11:51 在 神经阻滞麻醉 下拟行 颅内硬膜外脓肿引流术”
	if(valueArr['p_100_105002_352'] =='1'){
		html = yizhu_text + " " + fuss_text+buwei;
		
	}else{
		html = ss_data+" 在 "+mazui_text+" 下拟行 "+yizhu_text + " " + fuss_text+buwei;
	}
	//手术部位
	$($thistbody).find(".shoushu_yznr").val(html);
}

/* 手术双击右边列表新增一行 */

function addShoushuCyxm(obj)
{
	var params = activeTabParam();
	var ssHtml = $("#" + obj.id).text().trim();
	var flag;// 是否有空的input
	var ssLastInput = $("#"+params.tableId).find(".shoushu_yznr");
	$(ssLastInput).each(function(index, ele)
	{// 有空的input，追加添加
		if ($(ele).val() == "")
		{
			$(ele).focus();
			flag == false;
			$(ele).focus();
			activeAdviceInputId = $(ele).attr("id");//
			$("#" + activeAdviceInputId).val(ssHtml);
			if (obj)
			{
				if (obj.type == "zhiliaofangan")
				{// 治疗方案
					addShoushuBbxInfo(obj);
				}
				else if (obj.type == "cyxm" || obj.type == "treeTable")
				{
					addShoushuBbxInfo(obj);
				}
				else
				{
					editShoushuSetInfo(obj);
				}

			}
			return false;
		}
		if (index == $(ssLastInput).length - 1)
		{
			flag = true;
		}

	});
	if (flag)
	{
		shoushuAddTr($("#" + activeAdviceInputId));// 增加行
		var addlastInput = $("#"+params.tableId).find(".shoushu_yznr").last();
		activeAdviceInputId = $(addlastInput).last().attr("id");// 获取增加后的最后一行的遗嘱内容的input
		$("#" + activeAdviceInputId).val(ssHtml);
		if (obj)
		{
			if (obj.type == "zhiliaofangan")
			{
				addShoushuBbxInfo(obj);
			}
			else if (obj.type == "cyxm" || obj.type == "treeTable")
			{
				addShoushuBbxInfo(obj);
			}
			else
			{
				editShoushuSetInfo(obj);
			}

		}
		$(addlastInput).last().focus();
	}

	$($("#" + obj.id).siblings()[0]).val(obj.bbx01);
	$($("#" + obj.id).siblings()[1]).val(obj.bby01);
}

// //双击tree-table-tr的事件处理
function addShoushuBbxInfo(obj)
{
	var mzfs_text = '无';
	var curTr=$("#" + activeAdviceInputId).parents("tbody");
	if (obj.type == "cyxm" || obj.type == "treeTable")
	{

		curTr.attr(
		{
			'data-info' : JSON.stringify(obj)
		});
		$("#" + activeAdviceInputId).attr("data-name",obj.bbx05);
		
		curTr.find('.shoushu_yznr').next().val(obj.bbx01);// bbx01
		curTr.find('.shoushu_yznr').next().next().val(0);// bby01
		$(".changeTdDiv").hide();
		
		var robj = {
				bbx01:obj.bbx01,
				isManualTrigger:true,
				activeAdviceInputId:activeAdviceInputId
		}
		remaindByBbx01(robj);
	}
	else if (obj.type == "zhiliaofangan")
	{
		debugger;
		curTr.attr(
		{
			'data-info' : JSON.stringify(obj)
		});
		$("#" + activeAdviceInputId).attr("data-name",obj.bbx05);
		$("#" + activeAdviceInputId).val("在" + mzfs_text + "麻醉下拟执行 " + obj.bbx05);// 医嘱名称
		curTr.find('.shoushu_yznr').next().val(obj.bbx01c);// bbx01
		curTr.find('.shoushu_yznr').next().next().val(0);// bby01
		if(obj.mz){
			curTr.find(".shoushu_mzfs").find("select").val(obj.mz.bda01+"|"+obj.mz.bbx01c).trigger("change");
		}
		if(obj.bck01){
			curTr.find(".shoushu_zxks").find("select").val(obj.bck01).trigger("change");
		}
		$(".changeTdDiv").hide();
		if(obj.fjss){
			fujssAdd(obj.fjss);
		}
		curTr.find('.shoushu_buwei').val(obj.bef14);
		manualTriggerByparam(activeAdviceInputId);
	}
	setSsAdviceboxEvent(curTr);// 医嘱名称
	//关闭搜索框
	closeSelfLayer();
	//手动出发
	adviceCountShow();
}
function fujssAdd(fujiaArr){
	$(".shoushu_fjss").each(function(index, ele)
			{// 有空的input，追加添加
				if ($(ele).val() == "")
				{

					if (index < fujiaArr.length)
					{
						$(ele).val(fujiaArr[index]['bef07']);
						$(ele).next().val(fujiaArr[index]['bbx01c']);
					}
				}
			});
} 

// 手术编辑、
function editShoushuAdvice(dataObj)
{
	debugger;
	var param=activeTabParam();
	var fujiassArr = [];
	var bda01 = dataObj.bda01;
	if (bda01 == "S")
	{
//		$('#new_order_list a[href="#'+params.tabId+'"]').tab('show');
		// $("#operation").tab('show');//显示当前选中的链接及关联的content
		var url = rootUrl + "/doctoradviceeditor/getVaf1Byvaf01a";
		var params = {};
		params.vaf01 = dataObj.vaf01;
		$.ajax({url:url, type:"get",dataType:"json",data:params,async:false,success: function(data)
		{
			$('#new_order_list a[href="#'+param.tabId+'"]').trigger("click");
			var list = data.list;
			for (var i = 0; i < list.length; i++)
			{
				if (list[i].bda01 == 'A')
				{
					var mazui = list[i].bbx01;
					dataObj = $.extend(dataObj,
					{
						'mazui' : mazui
					});
				}
				else if (list[i].bda01 == 'S')
				{
					fujiassArr.push(list[i])
				}
			}
			dataObj.fujiassArr = fujiassArr;
			var url = rootUrl + "/doctoradvice/queryoperationscheduled";;
	    	var params= {};
	    	params.VAF01 = dataObj.vaf01;
	    	$.ajax({
	    		url:url,
	    		data:params,
	    		async:false,
	    		dataType:"json",
	    		type:"post",
	    		success:function(data){
	    			debugger;
		    		var list = data.list;
		    		var ssrenyuanArr=[];
		    		for(var i= 0;i<list.length;i++)
		    		{
		    			ssrenyuanArr.push(list[i]);
		    		}
		    		dataObj.ssrenyuanArr = ssrenyuanArr;
		    		addShoushuCyxm(dataObj);
		    		if (dataObj.type !="histroy")
					{
		    			$("#dataStr").val("");
						$("#cbm01").val(dataObj.cbm01);
					}
	    		}
	    	})
		}});
		
	}
}
// 编辑填充数据
function editShoushuSetInfo(editArr)
{
	debugger;
	var obj  = editArr.edit_data;
	var anesthesia  = editArr.anesthesia; //麻醉方式
	var operations  = editArr.operations; //附加手术
	var person  = editArr.person; //手术人员
	var i = 0,yznr;
	if(obj.vaf22.indexOf("下拟行")>-1){
		 yznr = obj.vaf22.split("下拟行 ")[1].split(" ")[0];
	}else{
		 yznr = obj.vaf22.split("下行 ")[1].split(" ")[0];
	}
	$("#" + activeAdviceInputId).attr("data-name",yznr);
	$("#" + activeAdviceInputId).val(obj.vaf22);// 医嘱名称
	$("#" + activeAdviceInputId).next().val(obj.bbx01);// bbx01
	$("#" + activeAdviceInputId).next().next().val(obj.bby01);// bby01
	var curTr=$("#" + activeAdviceInputId).parents("tbody");
	/* 附加手术TD */
	if(operations.length>0){
		var fjss = curTr.find(".shoushu_fjss");
		fjss.each(function(index, ele)
				{// 有空的input，追加添加
			if ($(ele).val() == "")
			{
				if (index < operations.length)
				{
					$(ele).val(operations[i].vaf22);
					$(ele).next().val(operations[i].bbx01);
					i++;
				}
			}
		});
	}
	//添加手术人员
	var s=0;
	if (person.length>0)
	{
		for (var n = 0; n < person.length; n++)
		{
			var renyuanS = curTr.find('.shoushu_ssry');
			if (person[n].ace01 == "01")
			{
				curTr.find('.shoushu_ssry_z').find("select").val(person[n].bce01).trigger("change");
			}
			else
			{
				$(renyuanS[s]).find("select").val(person[n].bce01).trigger("change");
				s++;
			}
		}
	}
	if(anesthesia.bbx01){
		curTr.find('.shoushu_mzfs').find("select").val("A|" + anesthesia.bbx01).trigger("change");;// 麻醉方式
	}
	curTr.find('.shoushu_sssj').val(obj.vaf14);// 手术时间
	curTr.find('.shoushu_pc').find("select option:contains('" + obj.vaf26 + "')").attr('selected', true).trigger("change");// 频次
	curTr.find('.shoushu_zl').val(obj.vaf21);// 总量
	curTr.find('.shoushu_zxks').find("select option:contains('" + obj.nbck03 + "')").attr('selected', true).trigger("change");// 执行科室
	curTr.find('.shoushu_mzzx').text();// 麻醉执行
	curTr.find('.shoushu_yszt').val(obj.bef15);// 医生嘱托
	curTr.find('.shoushu_zxfa').val(obj.bef22);// 执行方案?
	curTr.find('.shoushu_zzxz').find('select').val(obj.vaf58 + "").trigger("change");// 执行性质
	if(obj.vaf31){
		curTr.find('.shoushu_jjxz').find('select').val(obj.vaf31 + "").trigger("change");// 计价性质
	}
	curTr.find('.shoushu_buwei').val(obj.vaf15);
	if(obj.type !="histroy"){
		curTr.find('.shoushu_kzys').find("option:contains('" + obj.bce03a + "')").attr('selected', true);//开嘱医师--
		curTr.find('.shoushu_kzys').find("option:contains('" + obj.bce03a + "')").trigger("change");//开嘱医师--
	}
	$("#"+activeAdviceInputId).focus();
	setSsAdviceboxEvent(curTr);
	adviceCountShow();
}

// 全选事件
function ssChoseTr()
{
	var params = activeTabParam();
	var allCheck = "#"+params.tableId+" thead td:nth-of-type(1) input";
	var subcheck = "#"+params.tableId+" tbody td:nth-of-type(1) input";
	$(allCheck).on("click", function()
	{
		if ($(allCheck).is(':checked'))
		{
			$(subcheck).prop("checked", true);
		}
		else
		{
			$(subcheck).removeAttr("checked");
		}
	})

}

// 删除事

function ssDeleteTr()
{
	debugger;
	var params = activeTabParam();
		var arr = $("#"+params.tableId+" tbody td:nth-of-type(1) input:checked");
		var trArr = $("#"+params.tableId+" tbody tr");
		if (arr.length)
		{
			layer.confirm('确定要删除所选项',
			{
				btn : [
				'确定', '取消'
				],
				icon:3,
			// 按钮
			}, function()
			{
				$("#"+params.tableId+" tbody td:nth-of-type(1) input:checked").each(function()
				{ // 遍历选中的checkbox
					$(this).parents("tbody").remove();
				});
				layer.msg('删除成功',
				{
				time : 2000,
				icon : 1,
				skin: 'layui-layer-msg1'
				});
				if (arr.length * 8 == trArr.length)
				{
					addIndex_S = 1;
					shoushuTable();

				}
				adviceCountShow();
			}, function()
			{
			});
		}
		else
		{
			layer.msg('请选择要删除的处方',
			{
			time : 2000,
			icon : 0,
			skin: 'layui-layer-msg0'
			});
		}

}
//手术部位查询接口
function getShoushuBuweiData(){
	var def = $.Deferred();
	var text = $("#ss_check_input").val().replace(/[\r\n]/g,"");//获取到过滤换行符的字符串
	var reg= /^[A-Za-z]+$/; //判断是字母
	if (reg.test(text)){
		text = text.toUpperCase();
	}
	var txt = "'%"+text+"%'";
	var param = {params:JSON.stringify({sqlId:10000074,txt:txt})};
	$.ajax({
		type: "get",
		url: rootUrl+"/basicinformationquery/basequery",
		data:param,
		dataType: "json",
		success: function (resp) {
			def.resolve(resp.list);
		}
	});
	return def.promise();
}
//手术部位功能
function loadShoushuBuweitable(){
	layer.msg('加载中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500});
	$.when(
		getShoushuBuweiData()
	).done(function (data) {
		debugger;
		showDetailTable(data);
	});
}
//增加手术部位
function addSurgicalSite(){
	var tname = "ss_check_table";
	var ids = $("#"+tname).jqGrid('getGridParam','selarrrow');
	var arr = [];
	for (var i = 0; i < ids.length; i++)
	{
		var rowdata = $("#"+tname).jqGrid("getRowData", ids[i]);
		arr.push(rowdata.bbv02);
	}
	var str = arr.join(",");
	$("#"+activeAdviceInputId).parents("tbody").find(".shoushu_buwei").val(str);
	
}
function loadShoushuBuwei(that){
	activeAdviceInputId = $(that).parents("tbody").find(".shoushu_yznr").attr("id");
	laytplUrl(myurl + "/module/shoshu_buwei.html", {}, function(data1, html){
		var index = layer.open({
				type : 1,
				title : "手术部位",
				area : ["60%", "70%"],
				shade : 0.1,
				maxmin : true,
				content : html,
				closeBtn : 1,
				cancel:function(){
					
				},
				success : function()
				{
					loadShoushuBuweitable();
					$("#ss_check_cancle").on("click",function(){
						layer.close(index);
					});
					$("#ss_check_input").on("keyup",function(e){
						 var e = event || window.event || arguments.callee.caller.arguments[0];
				         if(e && e.keyCode==13){
				        	 loadShoushuBuweitable();
				         }
					});
					$("#ss_check_ok").on("click",function(){
						addSurgicalSite();
						setSsAdviceboxEvent($(that).parents("tbody"));
						layer.close(index);
					})
				}
			})
		});
}
function showDetailTable(data){
	$('#ss_check_table').GridUnload(); 
	$('#ss_check_container').resize(function(){
		$("#ss_check_table").setGridWidth($("#ss_check_container").width()*1);
	});
	$("#ss_check_table").jqGrid(
	{
	datatype: "local",
	data : data,
	height : 'auto',
	width : "100%",
	autowidth : true,
	rowNum:data.length,
	colModel : [
	    {label : '部位',name : 'bnq02'},
		{label : '检查部位',name : 'bbv02'},
		{label : 'abbrp',name : 'abbrp',hidden:true}
	],
	multiselect : true,
	loadComplete : function(data)
	{
		debugger
	},
	});
}
// 右侧常用诊断双击到诊断标签
function ssAddchangyongzhenduan(vao15, vao01)
{
	$("#sszds_select").tagsinput('add', vao01 + vao15);
}